// pages/goods/show.js
const app=getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods:[],
    selected:true,
    selected1:false,
    conetent:"",
    goods_num:"" 
  },
  selectBrief(e){
    this.setData({
      selected:true,
      selected1:false
    });
  },
  selectParameter(e){
    this.setData({
      selected:false,
      selected1:true
    });
  },
  //点击加入购物车按钮跳到商品属性选择页面
  toSelect(e){
    const id=e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url:`../selectGoods/selectGoods?id=${id}`
    });
  },
  goCart(){
    wx.switchTab({
      url: "../cart/cart"
    })
  },
  buyNow(e){
    var item_id=e.currentTarget.dataset.id;
    var item_sku_id=e.currentTarget.dataset.sku;
    app.getUserToken(function (err, token) {
      wx.request({
        url: app.globalData.url +'/index.php?s=api/cart/add',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method:'get',
          data: {item_id:item_id,item_sku_id:item_sku_id,goods_num:1,app_id:10001,token:app.globalData.token},
          success: (res) => {
              if(res.data.code==1){
                  wx.navigateTo({
                    url: '../payment/payment'
                  })
              }
          }
        })
      })
  },
  previewImage(e){
    const index=e.currentTarget.dataset.index;	//获取swiper里的图片的下标
		const slide=this.data.goods.goods_slides; //获取商品轮播图
    const imgList=[]; //定义一个数组来存放轮播图的url
    // console.log(slide);
		slide.map(item=>{
      imgList.push(item.slide_url);
    });
		wx.previewImage({
			current: imgList[index], // 当前显示图片的链接，不填则默认为 urls 的第一张
			urls: imgList
		})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const id=options.id;
    this.getPorducts(id);
  },

  getPorducts(options) {
    var that = this;
    wx.showLoading({
      title: '加载中...'
    })
    wx.request({
      url: app.globalData.url +'/index.php?s=api/item/detail',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'get',
        data: {item_id:options,app_id:10001},
        success: (res) => {
          if (res.data.code == 1){
            wx.hideLoading()
            that.setData({
              goods: res.data.data.detail,
              conetent:res.data.data.detail.goods_content.replace(/\<img/gi, '<img style="max-width:100%;height:auto"')
            })
          }
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  //把用户选好的商品规格从缓存拿出来
  onShow: function () {
    const goods_num=wx.getStorageSync('goods_sum');
    this.setData({
      goods_num
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})